class StoreOrder < ApplicationRecord
  paginates_per 10
  belongs_to :store_customer
  belongs_to :store
  has_many :items, class_name: "CartItem", as: :itemable

  before_create :set_numero

  enum status: %i[pending confirming processing mailing finished cancel]
  enum pay_status: %i[pay_pending pay_finished]

  scope :by_month_days, ->(date = Time.now) { where(created_at: date.prev_month .. date.end_of_day) }
  scope :available, -> { where.not(status: StoreOrder.statuses[:cancel]) }
  scope :by_date, ->(date=Time.now) { where(created_at: date.beginning_of_day .. date.end_of_day) }
  scope :unfinished, -> { where.not(status: [StoreOrder.statuses[:mailing], StoreOrder.statuses[:finished]]) }
  scope :complete, -> { where(status: [StoreOrder.statuses[:mailing], StoreOrder.statuses[:finished]]) }
  scope :by_week, ->(date = Time.now) { where(created_at: date.days_ago(6) .. date.end_of_day) }
  scope :by_store, ->(store_id) { where(store_id: store_id) if store_id.present? }
  scope :by_month, ->(month = Time.now) { where(created_at: month.beginning_of_month .. month.end_of_month) }


  def order_push
    OrderBroadcastJob.perform_now(self.store_id)
  end

  def items_count
    items.showable.count(:id)
  end

  def to_process!
    if self.pending?
      self.pending!
    end
    self.processing!
  end

  def to_mail!
    if self.processing?
      self.to_process!
    end
    self.mailing!
  end

  def status_i18n
    case status
    when "pending"
      "待处理"
    when "confirming"
      "已确认"
    when "processing"
      "处理中"
    when "mailing"
      "已发货"
    when "finished"
      "收货完成"
    when "cancel"
      "已取消"
    end
  end

  def pay_status_i18n
    case pay_status
    when "pay_pending"
      "未支付"
    when "pay_finished"
      "已支付"
    end
  end

  def format_created_at
    created_at.strftime("%Y-%m-%d %H:%M:%S")
  end

  def cancelable
    self.pending? || self.confirming?
  end

  def self.amount_by_month(month = Time.now)
    by_month(month).complete.sum(&:amount)
  end

  private
  def set_numero
    timestamp = Time.now.to_i.to_s(:number)
    self.numero = timestamp + generate_random(6)
  end

  def generate_random(length)
    chars = Array(0..9)
    length.times.map { chars.sample }.join
  end
end
